package servlet;

import service.UserService;

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;;

@WebServlet("/RegistServlet")
public class RegistServlet extends ServletBase {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
                          throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rep_password = request.getParameter("repeat_password");

        boolean registRequired = true;

        if (userService.conn == null)
            userService.getConnection();

        if (username == null || password == null || username.isEmpty() || password.isEmpty()
            || !password.equals(rep_password)) {
            registRequired = false;
        }

        if (registRequired && userService.userRegist(username, password)) {
            request.getRequestDispatcher("/web/login.jsp").forward(request, response);
            return;
        }
        request.setAttribute("msg", "Invalid Registration!!");
        request.getRequestDispatcher("/web/regist.jsp").include(request, response);
    }
}
